﻿using System;
using System.Windows.Forms;

using Moe.ECamel.Common.Entities;
using Moe.ECamel.Client.Controllers;
using Moe.ECamel.Client.WinForms.Common;
using Moe.ECamel.Client.WinForms.Forms;

namespace Moe.ECamel.Client.WinForms.Controls
{
	public partial class CustomerListControl : ECamelUserControl
	{
		private EntityController<Customer> _controller;

		public CustomerListControl()
		{
			InitializeComponent();
		}

		public void Initialize(EntityController<Customer> controller)
		{
			this._controller = controller;
			this.ListBindingSource.DataSource = _controller.List;
		}
		public void RefreshView()
		{
			// Refresh entity list:
			this._controller.RefreshList();
			// Refresh binding:
			this.ListBindingSource.CurrencyManager.Refresh();
			// Refresh menus:
			RefreshMenus();
		}
		private void RefreshMenus()
		{
			// Get current entity:
			var entity = ListBindingSource.Current;
			// Refresh available controls:
			bool hasValue = (entity != null);
			EntityViewToolStripButton.Enabled = EntityViewToolStripMenuItem.Enabled = hasValue;
			EntityEditToolStripButton.Enabled = EntityEditToolStripMenuItem.Enabled = hasValue;
		}

		private void AddEntity()
		{
			using (var form = new CustomerDetailsForm(_controller.NewCreateController()))
			{
				DialogResult result = form.ShowDialog();
				if (result == DialogResult.OK)
					RefreshView();				
			}
		}
		private void ViewEntity()
		{
			// Get current entity:
			var entity = (Customer)ListBindingSource.Current;
			if (entity != null)
			{
				using (var form = new CustomerForm(entity))
				{
					form.ShowDialog();
				}
			}
		}
		private void EditEntity()
		{
			// Get current entity:
			var entity = (Customer)ListBindingSource.Current;
			if (entity != null)
			{
				using (var form = new CustomerDetailsForm(_controller.NewEditController(entity)))
				{
					DialogResult result = form.ShowDialog();
					if (result == DialogResult.OK)
						RefreshView();
				}
			}
		}

		private void EntityAddToolStripButton_Click(object sender, EventArgs e)
		{
			AddEntity();
		}
		private void EntityViewToolStripButton_Click(object sender, EventArgs e)
		{
			ViewEntity();
		}
		private void EntityEditToolStripButton_Click(object sender, EventArgs e)
		{
			EditEntity();
		}

		private void EntityViewToolStripMenuItem_Click(object sender, EventArgs e)
		{
			ViewEntity();
		}
		private void EntityAddToolStripMenuItem_Click(object sender, EventArgs e)
		{
			AddEntity();
		}
		private void EntityEditToolStripMenuItem_Click(object sender, EventArgs e)
		{
			EditEntity();
		}

		private void ListDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			ViewEntity();
		}
	}
}